package com.atguigu.gulimall.member.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.atguigu.common.to.MemberLoginTo;
import com.atguigu.common.to.MemberRegistTo;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistedException;
import com.atguigu.gulimall.member.exception.UsernameExistedException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.gulimall.member.vo.SocialUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistTo to) {

        MemberEntity memberEntity = new MemberEntity();

        // 必须确保会员用户名和手机号的唯一性
        // 但是当前 regist 方法没有返回值，Controller 无法接收到返回值
        // 为了让 Controller 能感知到用户名和手机号是否唯一的校验结果，这里使用异常机制
        checkPhoneUnique(to.getPhone());
        checkUsernameUnique(to.getUsername());
        memberEntity.setUsername(to.getUsername());
        memberEntity.setMobile(to.getPhone());

        // 密码加密存储
        // spring-cloud-starter-openfeign 通过 spring-cloud-commons 间接引入了 spring-security-crypto 依赖
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(to.getPassword());
        memberEntity.setPassword(encode);

        // 设置默认会员等级
        MemberLevelEntity defaultLevelEntity = memberLevelService.getDefaultLevel();
        memberEntity.setLevelId(defaultLevelEntity.getId());

        memberEntity.setCreateTime(new Date());

        this.save(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistedException {
        if (this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone)) > 0) {
            throw new PhoneExistedException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistedException {
        if (this.count(new QueryWrapper<MemberEntity>().eq("username", username)) > 0) {
            throw new UsernameExistedException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginTo to) {
        // 前端用户可以使用用户名或手机号配合密码实现登录
        // 根据用户名或手机号查询用户信息
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", to.getLoginacct()).or().eq("mobile", to.getLoginacct()));

        if (memberEntity == null) {
            // 用户不存在
            return null;
        } else {
            // 校验登录密码是否正确
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            if (passwordEncoder.matches(to.getPassword(), memberEntity.getPassword())) {
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity oauthLogin(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();
        // 1.判断当前社交用户是否已经注册过
        MemberEntity memberEntity = this.getOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getSocialUid, uid));
        if (memberEntity != null) {
            // 已注册
            // 更新用户的社交登录用户令牌和令牌过期时间
            MemberEntity updateMemberEntity = new MemberEntity();
            updateMemberEntity.setId(memberEntity.getId());
            updateMemberEntity.setAccessToken(socialUser.getAccess_token());
            updateMemberEntity.setExpiresIn(String.valueOf(socialUser.getExpires_in()));
            this.updateById(updateMemberEntity);
            // 返回用户信息
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(String.valueOf(socialUser.getExpires_in()));
            return memberEntity;
        } else {
            // 未注册，需要查询当前社交用户的信息，保存到数据库中
            MemberEntity registerMemberEntity = new MemberEntity();
            try {
                // 使用 try catch 块，防止查询微博认证信息时出现异常影响谷粒商城用户登录功能
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSONUtil.parseObj(json);
                    String name = jsonObject.getStr("name");
                    String gender = jsonObject.getStr("gender");
                    String profileImageUrl = jsonObject.getStr("profile_image_url");

                    registerMemberEntity.setNickname(name);
                    registerMemberEntity.setGender("m".equals(gender) ? 1 : 0);
                    registerMemberEntity.setHeader(profileImageUrl);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            registerMemberEntity.setCreateTime(new Date());
            registerMemberEntity.setSocialUid(uid);
            registerMemberEntity.setAccessToken(socialUser.getAccess_token());
            registerMemberEntity.setExpiresIn(String.valueOf(socialUser.getExpires_in()));

            this.save(registerMemberEntity);
            return registerMemberEntity;
        }
    }
}